﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Cocon90.Lib.Util
{
    /// <summary>
    /// 日志记录工具
    /// </summary>
    public class Logger
    {
        public Logger(string LogDirectory)
        {

            this.LogDirectory = LogDirectory;
        }
        public string LogDirectory { get; set; }
        /// <summary>
        /// 写到日志
        /// </summary>
        /// <param name="msg"></param>
        public void addToLog(string msg)
        {
            string pth = LogDirectory;
            if (!System.IO.Directory.Exists(pth)) System.IO.Directory.CreateDirectory(pth);
            string log = String.Format("{0}{1}.txt", pth, DateTime.Now.ToLongDateString());
            FileStream fs;
            msg = msg ?? "";
            lock (msg)
            {
                lock (log)
                {
                    if (File.Exists(log))
                    {
                        fs = new FileStream(log, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                        lock (fs)
                        {
                            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                            sw.WriteLine(String.Format("{0}:{1}", DateTime.Now.ToLongTimeString(), msg));
                            sw.Close();
                            fs.Close();
                        }
                    }
                    else
                    {
                        fs = new FileStream(log, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                        lock (fs)
                        {
                            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                            sw.WriteLine(String.Format("{0}:{1}", DateTime.Now.ToLongTimeString(), msg));
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 将一个异常添加到日志记录
        /// </summary>
        /// <param name="exception"></param>
        public void addToLog(Exception exception)
        {
            addToLog("====================EXCEPTION====================");
            addToLog("异常信息:" + exception.Message);
            addToLog("错误源:" + exception.Source);
            addToLog("堆栈调用:" + exception.StackTrace);
            addToLog("产生异常的方法:" + exception.TargetSite.Name);
            addToLog("=================================================");
        }
    }
}
